<template>
    <div class="layout">
        <div class="container">
            <div class="container_right">
                <el-tabs v-model="activeName" @tab-change="switchTab">
                    <el-tab-pane
                        v-for="item in tabList"
                        :key="item.value"
                        :label="item.label"
                        :name="item.value"></el-tab-pane>
                </el-tabs>
                <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
                <ZwTable
                    ref="tableRef"
                    :select-all-group="true"
                    is-limit-height
                    class="table-box"
                    :option="tableOption"
                    :fetch-params="state.searchParams"
                    :row-key="getRowKey"
                    :fetch-api="fetchApi()"
                    @select="onSelect"
                    @selection-change="onSelectionChange"
                    @select-all="onSelectAll"
                    @select-all-change="onSelectAllChange"
                    @selectAllTotal="selectAllTotal">
                    <template #headerOperateLeft>
                        <div v-show="activeName == '2'" class="left">
                            <span v-auth="'SYNC_WECOM'" class="sync_hronize" @click="synchronizationFun(1)">
                                <el-icon v-if="loading" class="is-loading"><Loading /></el-icon>
                                <el-icon v-else class="sync_icon"><RefreshRight /></el-icon>
                                同步企微客户
                            </span>
                            <span>最近同步时间：{{ updateTime }}</span>
                        </div>
                        <div v-show="activeName == '4'" class="left">
                            <span v-auth="'SYNC_WECOM'" class="sync_hronize" @click="synchronizationFun(10)">
                                <el-icon v-if="loading" class="is-loading"><Loading /></el-icon>
                                <el-icon v-else class="sync_icon"><RefreshRight /></el-icon>
                                同步抖音客户
                                <el-tooltip
                                    class="box-item"
                                    content="同步授权抖音企业号的粉丝、意向用户"
                                    placement="top">
                                    <el-icon color="#ccc"><QuestionFilled /></el-icon>
                                </el-tooltip>
                            </span>
                            <span>最近同步时间：{{ updateTime }}</span>
                        </div>
                    </template>
                    <template #headerOperate>
                        <el-button plain @click="router.push('/customer/manage/list/audit')">协助人审核</el-button>
                        <el-dropdown class="dropdown_btn" @command="v => onBatch(v)">
                            <el-button plain :disabled="disabled()">
                                批量操作
                                <el-icon class="el-icon--right">
                                    <arrow-down />
                                </el-icon>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-auth="'BATCH_MARK'" :disabled="disabled()" command="1">
                                        批量打标签
                                    </el-dropdown-item>
                                    <el-dropdown-item v-auth="'BATCH_MARK'" :disabled="disabled()" command="4">
                                        批量移除标签
                                    </el-dropdown-item>
                                    <el-dropdown-item v-auth="'BATCH_ASSIGN'" :disabled="disabled()" command="2">
                                        批量分配
                                    </el-dropdown-item>
                                    <el-dropdown-item
                                        v-auth="'EXPORT_CUSTOMER'"
                                        :disabled="disabled()"
                                        command="3"
                                        @click="getClickPosition">
                                        导出客户
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <el-dropdown class="dropdown_btn" @command="onAddCustomer">
                            <el-button type="primary">
                                添加客户<el-icon class="el-icon--right"><arrow-down /> </el-icon>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-auth="'ADD_CUSTOMER'" command="1"> 单个添加 </el-dropdown-item>
                                    <el-dropdown-item v-auth="'IMPORT_CUSTOMER'" command="2">
                                        批量导入
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </ZwTable>
            </div>
        </div>
    </div>
    <!-- 删除弹框 -->
    <AddCustomer ref="AddCustomerRef" v-model="addCustomerVisible" @submit="addCustomerSave" />
    <AddFollow ref="AddFollowRef" @save="addFollowSave" />
    <ZWDepart ref="DepartRef" :is-local="true" @submit="getZWDepartData" />
    <!--批量打标签/移除标签-->
    <ZwBatchLabel ref="BatchLabelRef" @save="getTagsFun"></ZwBatchLabel>
    <ImportCustomer
        ref="ImportCustomerRef"
        :multiple="false"
        :batch-import-type="1"
        @save="onImportCustomer"
        @cancel="closeImportCustomer" />

    <Dialog :app-dialog="appDialog">
        <div class="msg">
            您即将【批量{{ batchType == 1 ? '打标签' : batchType == 4 ? '移除标签' : '分配' }}】<span class="msg_num">{{
                selectTableTotal
            }}</span>
            条数据，确认要执行此操作吗？
        </div>
    </Dialog>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CUSTOMER_MANAGE_LIST' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import AddFollow from './components/AddFollow.vue';
import AddCustomer from '@/components/customerCenter/AddCustomer.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import ImportCustomer from './components/ImportCustomer.vue';
import Dialog from '@/components/Dialog.vue';

import useClipboard from 'vue-clipboard3';
import { ElMessage, ElLoading } from 'element-plus';
import {
    getCenterCustomerList,
    exportCustomer,
    batchAssignStaff,
    batchAddTag,
    batchRmTag,
    batchAssignStaffAsync
} from '@/api/customerCenter';
import { getSyncTime, custSync, custSyncResult, tiktokSync, fllowTiktok } from '@/api/customerCenter/groupManage';
import cityData from '@/assets/js/city';
import { stageList, sourceList } from '../configure/api';
import { tiktokList } from '@/api/customerCenter';
import { ref, reactive, computed, onActivated, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { DOWLOAD_FILE } from '@/utils/smartMarketing';
import { useStore } from '@/store';
import { renderCustInfo } from './components/TableColumn.tsx';
import { defaultTime } from '@/utils/utils';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const store = useStore();
const DeletdialogRef: any = ref(null);
const router = useRouter();
const GroupingRef: any = ref(null);
const isShow = ref(0);
const checkList = ref([]);
const delId = ref<any>([]);
const targetArr = reactive<Array<any>>([]);
const loading = ref<boolean>(false);
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const batchType = ref();

const cancelHandel = () => {
    batchType.value = '';
    appDialog.visible = false;
};
const submitHandel = e => {
    clickEvent = e;
    switch (batchType.value) {
        case '1':
            batchMarking();
            break;
        case '2':
            batchAssignStaffFun1();
            break;
        case '4':
            batchMarking();
            break;
    }
    tableRef.value.clearAllSelect();
    tableRef.value.clearSelection();
};

// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: '批量结束',
    width: '400px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [], // 传递进来选中的数据
    params: {
        isAll: false
    }
});

// 是否禁用批量操作
const disabled = () => {
    if (checkList.value.length > 0 || selectTableTotal.value > 0) {
        return false;
    } else {
        return true;
    }
};

const selectTableTotal = ref(0);

const selectAllTotal = (value: any) => {
    selectTableTotal.value = value;
};

const cancleAllArray = ref([]);
const onSelectAllChange = (val: any) => {
    cancleAllArray.value = val;
};

const activeName = ref('0');
const tabList = reactive([
    { label: '全部客户', value: '0' },
    { label: '企微客户', value: '2' },
    { label: '抖音客户', value: '4' },
    { label: '其他客户', value: '1' }
]);
const switchTab = () => {
    reset();
    if (['2', '4'].includes(activeName.value)) {
        getSyncTimeFun();
    }
};
const defaultParams = {
    mobile_or_name: '',
    work_user_id: [],
    is_wx_work: -1,
    tiktok_number: '',
    stage: 0,
    protect: '',
    work_user_ids: [],
    touch_mode: -1,
    select_tag_type: -1,
    tag_ids: [],
    cust_status: -1,
    address: '',
    group_chat: [],
    created_time: [],
    add_time: [],
    cust_channel: activeName.value,
    has_mobile: -1
};

const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'code'
};

// 复制
const { toClipboard } = useClipboard();
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const tableRef = ref<any>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    const option = [
        {
            label: '客户信息',
            name: 'mobile_or_name',
            value: '',
            type: 'input',
            placeholder: '请输入客户手机号｜姓名｜昵称搜索'
        },
        {
            label: '客户来源',
            name: 'source_id',
            value: [],
            type: 'select',
            placeholder: '请选择客户来源',
            multiple: true,
            collapseTags: true,
            filterable: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    sourceList({ page: 1, page_size: 99999 }).then((r: any) => {
                        r.data = r.data || [];
                        resolve(r.data);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '企微好友',
            name: 'is_wx_work',
            value: -1,
            type: 'select',
            placeholder: '请选择是否添加企微好友',
            optionList: [
                {
                    label: '不限制',
                    value: -1
                },
                {
                    label: '是',
                    value: 1
                },
                {
                    label: '不是',
                    value: '0'
                }
            ]
        },
        {
            label: '抖音企业号',
            name: 'tiktok_number',
            value: '',
            type: 'select',
            placeholder: '请选择抖音企业号',
            filterable: true,
            // alway: true,         //  是否一直刷新接口  默认为false
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    const params = {
                        action: 'select_list'
                    };
                    tiktokList(params).then((res: any) => {
                        resolve(res);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.nickname,
                value: v.id
            })
        },
        {
            label: '客户阶段',
            name: 'stage',
            value: '',
            type: 'select',
            placeholder: '请选择客户阶段',
            filterable: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    stageList({ page: 1, page_size: 99999 }).then((r: any) => {
                        resolve([{ id: 0, name: '全部' }, ...r]);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '客户保护',
            name: 'protect',
            value: '',
            type: 'select',
            placeholder: '请选择是否添加客户保护',
            optionList: [
                {
                    label: '全部',
                    value: '0'
                },
                {
                    label: '未保护',
                    value: 1
                },
                {
                    label: '已保护',
                    value: 2
                }
            ]
        },
        {
            label: '归属员工',
            name: 'work_user_ids',
            value: [],
            type: 'select',
            placeholder: '请选择归属员工',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            filterable: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '触达方式',
            name: 'touch_mode',
            value: -1,
            type: 'select',
            placeholder: '请选择客户触达方式',
            optionList: [
                { label: '全部', value: -1 },
                { label: '短信', value: '0' },
                { label: '企业微信', value: 1 },
                { label: '微信', value: 2 },
                { label: '抖音消息', value: 3 },
                { label: '公众号', value: 4 },
                { label: '邮箱', value: 5 }
            ]
        },
        {
            label: '客户标签',
            name: 'tag_ids',
            value: [],
            type: 'select',
            tagTypeName: 'select_tag_type',
            multiple: true,
            isBatchLabel: true,
            popperClass: 'zw-hide_select_option'
        },
        {
            label: '客户状态',
            name: 'cust_status',
            value: -1,
            type: 'select',
            placeholder: '请选择客户状态',
            optionList: [
                { label: '全部', value: -1 },
                { label: '已流失', value: '0' },
                { label: '正常', value: 1 },
                { label: '异常', value: 2 }
            ]
        },
        {
            label: '所在地',
            name: 'address',
            value: '',
            options: cityData,
            props: defaultProps,
            type: 'cascader',
            optionList: []
        },
        {
            label: '所在企微群',
            name: 'group_chat',
            value: '',
            type: 'select',
            placeholder: '请选择所在企微群',
            popperClass: 'zw-hide_select_option',
            isGroupSelect: true,
            multiple: true,
            echoTypeFlag: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: defaultTime(),
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '添加时间',
            name: 'add_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: defaultTime(),
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '手机号客户',
            name: 'has_mobile',
            value: -1,
            type: 'select',
            placeholder: '请选择手机号客户',
            optionList: [
                { label: '不限制', value: -1 },
                { label: '有手机号', value: 1 },
                { label: '无手机号', value: 2 }
            ]
        },
        {
            label: '可联系员工',
            name: 'contact_work_user_ids',
            value: [],
            type: 'select',
            placeholder: '请选择可联系员工',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            filterable: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
    const wxworkkey = {
        1: ['is_wx_work', 'tiktok_number', 'address'],
        2: ['is_wx_work', 'group_chat', 'add_time']
    }[activeName.value];
    return wxworkkey ? option.filter((v: any) => !wxworkkey.includes(v.name)) : option;
});
const search = (v: any) => {
    currentParams.value = v;
    if (v.is_wx_work === '') {
        v.is_wx_work = -1;
    }
    if (v.cust_status === '') {
        v.cust_status = -1;
    }
    if (v.touch_mode === '') {
        v.touch_mode = -1;
    }
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v,
        cust_channel: activeName.value
    };
    tableRef.value.clearSelection();
    tableRef.value.clearAllSelect();
};
const reset = (v?: any) => {
    tableRef.value.clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), cust_channel: activeName.value };
    currentParams.value = null;
    tableRef.value.clearAllSelect();
};
// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '客户信息',
        width: 200,
        fixed: 'left',
        render: renderCustInfo
    },
    {
        prop: 'mobile',
        label: '手机号',
        width: 120
    },
    {
        prop: 'tag_info',
        label: '客户标签',
        isTag: true,
        width: 220
    },
    {
        prop: 'touch_list',
        label: '触达方式',
        width: 240,
        render({ row, column, index }: any) {
            return row.touch_list ?? '--';
        }
    },
    {
        prop: 'is_wx_work',
        label: '企微好友',
        width: 120,
        render({ row, column, index }: any) {
            return row.is_wx_work ? '是' : '否';
        }
    },
    {
        prop: 'can_contact',
        label: '可联系员工',
        width: 120,
        render({ row, column, index }: any) {
            const arr = row.can_contact?.split('、');
            return (
                <>
                    <div vShow={arr && arr.length > 1}>
                        <el-tooltip class="item" effect="dark" content={row.can_contact} placement="top-start">
                            <div class="zw-text-ellipsis">{row.can_contact}</div>
                        </el-tooltip>
                    </div>
                    <div vShow={arr && arr.length == 1}>{row.can_contact?.split('、')}</div>
                    <div vShow={!arr}>--</div>
                </>
            );
        }
    },
    {
        prop: 'assign_employees',
        label: '归属员工',
        width: 120,
        render({ row, column, index }: any) {
            return row.assign_employees ?? '未分配';
        }
    },
    {
        prop: 'source_name',
        label: '客户来源',
        width: 200,
        render({ row, column, index }: any) {
            return row.source_name ?? '--';
        }
    },
    {
        prop: 'current_stage_name',
        label: '客户阶段',
        width: 200,
        render({ row, column, index }: any) {
            return row.current_stage_name ?? '--';
        }
    },
    {
        prop: 'add_time',
        label: '最早添加时间',
        minWidth: 175,
        render({ row, column, index }: any) {
            return row.add_time ?? '--';
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        minWidth: 175,
        render({ row, column, index }: any) {
            return row.created_at ?? '--';
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 280,
        fixed: 'right',
        isOperate: true,
        option: [
            { name: '详情', authCode: 'VIEW_DETAIL', click: (row: any) => toDetail(row) },
            {
                name: '分配员工',
                authCode: 'RE_ASSIGN',
                click: (row: any) => openDepart('one', row),
                isRender: ({ row }: any) => row.cust_assign_status == 0
            },
            {
                name: '重新分配',
                authCode: 'RE_ASSIGN',
                click: (row: any) => openDepart('one', row),
                isRender: ({ row }: any) => row.cust_assign_status == 1
            },
            {
                name: '客户转交',
                authCode: 'RE_ASSIGN',
                click: (row: any) => openDepart('one', row),
                isRender: ({ row }: any) => row.cust_assign_status == 2
            },
            {
                name: '查看',
                authCode: 'VIEW',
                click: (row: any) => openAddCustomer(row, 'look')
            },
            {
                name: '添加跟进',
                authCode: 'ADD_FOLLOW_UP',
                click: (row: any) => showAddFollowFun(row)
            },
            {
                name: '编辑',
                authCode: 'EDIT',
                click: (row: any) => openAddCustomer(row, 'edit')
            },
            {
                name: '添加商机',
                authCode: 'ADD_BUSINESS',
                click: (row: any) => router.push(`/salesleads/salesmanagement/business/create?customer=${row.id}`)
            }
        ]
    }
];
const addCustomerVisible = ref<boolean>(false);

const AddFollowRef = ref<any>();
// 添加跟进
const showAddFollowFun = (val: any) => {
    if (!val.id) {
        ElMessage.error('当前数据异常,请稍后再试');
        return;
    }
    AddFollowRef.value.followId = val.id;
    AddFollowRef.value.drawerData.userInfo = val;
    AddFollowRef.value.drawerData.show = true;
};
// 查看
const AddCustomerRef = ref<any>();
const openAddCustomer = (row: any, type: string) => {
    row && (AddCustomerRef.value.drawerData.userInfo = row);
    AddCustomerRef.value.drawerData.controlType = type;
    addCustomerVisible.value = true;
};
// 前往详情页
const toDetail = (val: any) => {
    if (!val.id) {
        ElMessage.error('当前数据异常，请刷新页面');
        return;
    }
    router.push(`/customer/manage/list/detail?id=${val.id}&type=${val.type}`);
};

const DepartRef = ref<any>();
const departTypeObj: any = {
    departType: '', //当前打卡选择员工的类型
    departData: [], //选中的数据
    itemData: '' //当前传入的数据
};
// 获取当前选中的员工的数据
const getZWDepartData = (val?: any, flag?: boolean) => {
    if (departTypeObj.departType != 'formData') {
        departTypeObj.departData = val;
        batchAssignStaffFun(departTypeObj.departType != 'one');
    }
};
//打开新建选择人
const openDepart = (type: string, data: any) => {
    departTypeObj.departType = type;
    if (type != 'formData') {
        departTypeObj.departData = [];
    }
    if (data) {
        departTypeObj.itemData = data;
        // 未分配
        if (data.cust_assign_status == 0) {
            DepartRef.value.selectedMember = [];
        }
        if (data.cust_assign_status == 1) {
            // 客户转交
            DepartRef.value.disabledSelected = [data.cust_distribution?.work_user?.id];
            DepartRef.value.selectedMember =
                data.distribution_work_userid != 0
                    ? [
                          {
                              name: data.assign_employees,
                              id: data.distribution_work_userid,
                              type: 'user'
                          }
                      ]
                    : [];
        }

        DepartRef.value.multiple = false;
    } else {
        departTypeObj.itemData = {};
        DepartRef.value.multiple = true;
        DepartRef.value.selectedMember = [];
    }
    DepartRef.value.departVisble = true;
    DepartRef.value.title = '选择员工';
};
const getRowKey = (row: any) => {
    return row.id;
};
const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return new Promise(resolve => {
        resolve((data: any) => {
            return getCenterCustomerList(data, true);
        });
    });
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {
    checkList.value = selection.map(v => v.id);
};
// 全选
const onSelectAll = selection => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};

// 单个添加保存
const addCustomerSave = () => {
    tableRef.value.clearAllSelect();
    tableRef.value.clearSelection();
    reloadTable();
};

// 添加跟进保存
const addFollowSave = () => {
    tableRef.value.clearAllSelect();
    tableRef.value.clearSelection();
    reloadTable();
};

// 批量分配员工
const batchAssignStaffFun = (isAll: boolean) => {
    if (batchType.value == 2 && departTypeObj.departType != 'one') {
        appDialog.title = '批量分配';
        appDialog.visible = true;
        appDialog.params.isAll = isAll;
    } else {
        if (!isAll) {
            batchAssignStaffFun1();
        }
    }
};
/**
 * 分配员工方法
 * 根据 departTypeObj.departType 区分批量分配还是单个分配
 */
const batchAssignStaffFun1 = async () => {
    const customer_list = appDialog.params.isAll ? checkList.value : [departTypeObj.itemData.id];
    let work_user_list = departTypeObj.departData.map((it: any) => {
        return it.id;
    });
    work_user_list = departTypeObj.departType == 'one' ? [work_user_list[work_user_list.length - 1]] : work_user_list;

    let params = {
        select_type: 1,
        customer_list,
        work_user_list
    };
    // 单个分配
    if (departTypeObj.departType == 'one') {
        batchAssignStaff({
            customer_list: [departTypeObj.itemData.id],
            work_user_list
        })
            .then((r: object) => {
                reloadTable();
                ElMessage.success('分配成功');
                tableRef.value.clearAllSelect();
                tableRef.value.clearSelection();
                appDialog.visible = false;
            })
            .catch((e: object) => {
                // ElMessage.warning(e)
            });
    } else if (departTypeObj.departType == 'batch') {
        // 批量分配
        if (tableRef.value.getIsSelectAll()) {
            params = {
                select_type: 2,
                customer_list: cancleAllArray.value,
                work_user_list,
                ...state.searchParams
            };
        }
        await batchAssignStaffAsync(params);
        parabolaAnimation(clickEvent);
        reloadTable();
        ShowTaskMessage('批量分配异步任务创建成功');
        appDialog.visible = false;
    }
};

const BatchLabelRef = ref<any>(null);
const labelObj: any = {
    type: '', //当前打开选择标签是哪个类型
    data: [] //选中标签的数据存储
};
// 打开选择标签弹框
const openBatchLabel = (num: number) => {
    BatchLabelRef.value.dialogVisible = true;
    BatchLabelRef.value.title = num == 1 ? '批量打标签' : '批量移除标签';
    BatchLabelRef.value.hasConditiion = false;
    BatchLabelRef.value.chooseDataArr = [];
};
// 获取当前选中的标签
const getTagsFun = async (val?: any) => {
    appDialog.visible = true;
    appDialog.title = batchType.value == 1 ? '批量打标签' : '批量移除标签';
    appDialog.params = val;
};

// 批量打标
const batchMarking = async () => {
    const val = { ...appDialog.params };
    let param = {
        select_type: 1,
        customer_list: checkList.value,
        tag_list: val.idList,
        is_batch: 1
    };
    // {
    //     "select_type": 1, // 列表选择类型 1-表示选中的，后端默认设置为1，2-表示全选 ids为空时表示全部，不为空时表示要排除的
    //     "ids": [] // ids是原有的参数，不用调整，原来名称是什么就是什么
    // }
    // select_type 2是全选 1是默认兼容原来的
    // 全选打标
    if (tableRef.value.getIsSelectAll()) {
        param = {
            select_type: 2,
            customer_list: cancleAllArray.value,
            tag_list: val.idList,
            ...state.searchParams,
            is_batch: 1
        };
    }
    //  3批量打标签  4 批量删除标签
    const res = batchType.value == 1 ? await batchAddTag(param) : await batchRmTag(param);
    parabolaAnimation(clickEvent);
    ShowTaskMessage(`批量${batchType.value == 1 ? '打' : '移除'}标签异步任务创建成功`);
    appDialog.visible = false;
    reloadTable();
};
// 导出客户数据
const exportCustomerFun = () => {
    const arr = [...checkList.value];
    let params = { select_type: 1, cust_Ids: arr, ...currentParams.value };
    if (tableRef.value.getIsSelectAll()) {
        params = {
            select_type: 2,
            cust_Ids: cancleAllArray.value,
            ...state.searchParams
        };
    }
    exportCustomer(params)
        .then(() => {
            parabolaAnimation(clickEvent);
            ShowTaskMessage('批量导出异步任务创建成功');
            tableRef.value.clearSelection();
            tableRef.value.clearAllSelect();
        })
        .catch((e: object) => {
            // console.log(e, 555);
        });
};
let clickEvent: any = null;
const getClickPosition = e => {
    clickEvent = e;
};
const onBatch = (command: string, e) => {
    batchType.value = command;
    command == '1' && openBatchLabel(1);
    command == '2' && openDepart('batch', '');
    command == '3' && exportCustomerFun();
    command == '4' && openBatchLabel(4);
};

// 打开导入客户的弹框
const ImportCustomerRef = ref<any>();
const openImportCustomer = () => {
    ImportCustomerRef.value.appDialog.visible = true;
};
// 保存批量导入
const onImportCustomer = e => {
    parabolaAnimation(e);
    tableRef.value.clearAllSelect();
    tableRef.value.clearSelection();
    reloadTable();
};
// 关闭导入的弹框
const closeImportCustomer = () => {
    DepartRef.value.departVisble = false;
};

const onAddCustomer = (command: string) => {
    if (command == '1') {
        AddCustomerRef.value.drawerData.userInfo = null;
        AddCustomerRef.value.drawerData.controlType = 'create';
        addCustomerVisible.value = true;
    }
    command == '2' && openImportCustomer();
};

let timeId: any = '';
// let loading: any = ''
const checkSuccessSync = (jobid: string, type: any) => {
    custSyncResult({ jobid, type }).then((r: any) => {
        loading.value = true;
        // loading = ElLoading.service({
        //   lock: false,
        //   text: '同步中....',
        //   background: 'rgba(0, 0, 0, 0.7)'
        // })
        if (!r) {
            loading.value = false;
            // loading.close()
            timeId = '';
            ElMessage.error('同步失败');
            return;
        }
        if (r.status > 1) {
            loading.value = false;
            // loading.close()
            clearInterval(timeId);
            getSyncTimeFun();
            reloadTable();
            timeId = '';
            ElMessage[r.status == 2 ? 'success' : 'error'](r.status == 2 ? '同步成功' : '同步失败');
        } else {
            if (!timeId) {
                timeId = setInterval(() => {
                    checkSuccessSync(jobid, type);
                }, 3000);
            }
            reset();
        }
    });
};
// 同步企业微信
const synchronizationFun = async (type: number) => {
    if (type == 1) {
        const res = await custSync({ type: type });
        checkSuccessSync(res.jobid, type);
    } else {
        const res = await tiktokSync();
        checkSuccessSync(res.jobid, type);
    }
};

const updateTime = ref<string>();
// 获取最新同步时间
const getSyncTimeFun = () => {
    let sync_type: number;
    switch (activeName.value) {
        case '2':
            sync_type = 120;
            break;
        case '4':
            sync_type = 121;
            break;
        default:
            sync_type = 120;
            break;
    }
    getSyncTime({ sync_type }).then((r: any) => {
        updateTime.value = r.weiwork_synctime;
    });
};

onActivated((val: any) => {
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...currentParams.value,
        cust_channel: activeName.value
    };
    tableRef.value.clearSelection();
    tableRef.value.clearAllSelect();
});

// getSyncTimeFun()
</script>

<style lang="scss" scoped>
.layout {
    .container {
        display: flex;

        .container_right {
            flex: 1;
            padding: 6px 24px 24px;
            box-sizing: border-box;
            background: #fff;
            border: 1px solid #eaeaea;
            overflow: hidden;
        }
    }
}

.dropdown_btn {
    margin-left: 10px;
}

:deep(.avatar-box) {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .avatar {
        width: 50px;
        height: 50px;
        border-radius: 4px;
    }

    .image-slot {
        .el-icon {
            font-size: 50px;
        }
    }

    .name {
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #33302d;
        max-width: 90px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
        margin: 0 10px;
    }

    .sex {
        width: 18px;
        height: 18px;
    }
}

.left {
    display: flex;

    .sync_hronize {
        display: flex;
        align-items: center;
        margin-right: 10px;
        color: #ff6b00;
        cursor: pointer;
    }

    .select-box {
        padding: 0 12px;
        border: 1px solid #eaeaea;
        background: #f9f9f9;
        border-radius: 1px;
        margin-right: 28px;

        .el-input__inner {
            border: none;
        }
    }

    span {
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #33302d;
        line-height: 44px;
    }
}

:deep(.crop) {
    display: flex;
    align-items: center;

    .crop_awatar {
        width: 50px;
        height: 50px;
        margin-right: 10px;
    }

    .crop_info {
        .crop_name {
            width: 130px;
            height: 23px;
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .crop_contact {
            font-size: 12px;
            color: #969696;

            .crop_contact_look {
                color: #ff6b00;
                cursor: pointer;
            }
        }
    }
}

.msg {
    text-align: center;
    padding: 50px 0;

    &_num {
        color: #ff6b00;
    }
}
</style>
